<template>
  <div>
    <px-row style="height: 64px">
      <px-col :span="24" class="water_col">
        <div class="waterdom borderRidus">
          <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
            <px-form-item label="年份">
              <px-date-picker v-model="queryParams.particularYear" format="YYYY" value-format="YYYY" type="year" placeholder="请选择年份" />
            </px-form-item>
            <px-form-item label="厂区">
              <px-select v-model="queryParams.level" :disabled="facDisabled" placeholder="请选择厂区" clearable style="width: 210px" filterable>
                <px-option v-for="dict in liquidList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>

            <px-form-item label="核算边界">
              <px-select v-model="queryParams.templateId" placeholder="请选择核算边界" clearable style="width: 210px" filterable>
                <px-option v-for="dict in templateList" :key="dict.boundaryId" :label="dict.templateName" :value="dict.id" />
              </px-select>
            </px-form-item>
            <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery()">查询</px-button>
            <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
          </px-form>
        </div>
      </px-col>
    </px-row>
    <px-row style="height: 272px; margin-top: 16px">
      <px-col v-if="summary != null" :span="8" class="water_col">
        <div class="waterdom borderRidus first_width">
          <modelTitle :title="'配额总览'" />
          <div class="model_chart">
            <img class="co2img" src="@/assets/images/co2.png" />
            <p class="titlep">配额总量</p>
            <div class="titlevalue">
              <p class="titlevalue1">{{ summary?.totalQuota }}<span class="titlevalue1span"> tCO2e</span></p>
              <p class="titlevalue2 !ml-16">
                年度同比 <span> {{ summary?.yearOnYearRatio != null ? summary?.yearOnYearRatio : "-" }}%</span>
              </p>
              <px-icon v-if="summary?.yearOnYearRatio > 0" style="margin-top: 8px" color="#F87171">
                <Top />
              </px-icon>
              <px-icon v-if="summary?.yearOnYearRatio < 0" style="margin-top: 8px" color="#39c670">
                <Bottom />
              </px-icon>
            </div>
            <div class="co2mian">
              <div class="co2mianleft">
                <p class="co2mianleftp">已消耗配额</p>
                <p class="co2mianleftp2">{{ summary?.alreadyConsume }}<span class="co2mianleftp2span"> tCO2e</span></p>
                <p class="co2mianleftp3">
                  截止本月同比 <span> {{ summary?.monthOnMonthRatio != null ? summary?.monthOnMonthRatio : "-" }}%</span>
                </p>
                <px-icon v-if="summary?.monthOnMonthRatio > 0" style="margin-top: 2px" color="#F87171">
                  <Top />
                </px-icon>
                <px-icon v-if="summary?.monthOnMonthRatio < 0" style="margin-top: 2px" color="#39c670">
                  <Bottom />
                </px-icon>
              </div>
              <div class="co2mianright">
                <p class="co2mianrightp">日均消耗配额</p>
                <p class="co2mianleftp2" style="margin-left: 45px">{{ summary?.dailyConsumption }}<span class="co2mianleftp2span"> tCO2e</span></p>
              </div>
            </div>
          </div>
        </div>
      </px-col>
      <px-col v-else :span="8" class="water_col">
        <div class="waterdom borderRidus first_width"><modelTitle :title="'配额总览'" /><px-empty :image-size="100" /></div>
      </px-col>
      <px-col v-if="summary != null" :span="16" class="water_col">
        <div class="waterdom borderRidus">
          <modelTitle :title="'配额剩余量'" />
          <div class="title-right" style="right: 32px">
            <px-tooltip effect="dark" content="导出数据">
              <px-button type="primary" text :icon="Document" @click="handleExport" />
            </px-tooltip>
          </div>
          <div class="model_chart">
            <px-row style="width: 100%; height: 100%">
              <!-- <px-col :span="4">
                <px-progress class="jindu1" type="dashboard" color="#3B82F6" stroke-width="12" :percentage="34.08" width="132">
                  <template #default>
                    <span class="percentage-label">剩余</span>
                    <span class="percentage-value">34.08%</span>
                  </template>
</px-progress>
<p class="jindu1p">STIC</p>
</px-col> -->
              <px-col v-for="(item, index) in summary?.levelConsume" :key="index" :span="4">
                <px-tooltip
                  class="box-item"
                  effect="dark"
                  :content="`	配额总量 ${item.totalQuota}tCO2e，已消耗配额 ${item.alreadyConsume ? item.alreadyConsume : '0'}tCO2e`"
                  placement="top"
                >
                  <px-progress
                    v-if="item.totalQuota == 0 && item.alreadyConsume == 0"
                    class="jindu1"
                    type="dashboard"
                    color="#3B82F6'"
                    stroke-width="12"
                    :percentage="0"
                    width="109"
                  >
                    <template #default>
                      <span style="color: #ccc">暂无</span>
                    </template>
                  </px-progress>
                  <px-progress
                    v-else
                    class="jindu1"
                    type="dashboard"
                    :color="(((item.totalQuota - item.alreadyConsume) / item.totalQuota) * 100).toFixed(2) > 0 ? '#3B82F6' : 'red'"
                    stroke-width="12"
                    :percentage="(((item.totalQuota - item.alreadyConsume) / item.totalQuota) * 100).toFixed(2)"
                    width="109"
                  >
                    <template #default>
                      <span v-if="(((item.totalQuota - item.alreadyConsume) / item.totalQuota) * 100).toFixed(2) > 0" class="percentage-label1"
                        >剩余</span
                      >

                      <span v-else class="percentage-label1" style="color: red">超标</span>
                      <span v-if="(((item.totalQuota - item.alreadyConsume) / item.totalQuota) * 100).toFixed(2) > 0" class="percentage-value"
                        >{{ Math.abs((((item.totalQuota - item.alreadyConsume) / item.totalQuota) * 100).toFixed(2)) }}%</span
                      >

                      <span v-else class="percentage-value" style="color: red"
                        >{{ Math.abs((((item.totalQuota - item.alreadyConsume) / item.totalQuota) * 100).toFixed(2)) }}%</span
                      >
                    </template>
                  </px-progress>
                </px-tooltip>

                <p class="jindu1p">{{ item.level }}</p>
              </px-col>
            </px-row>
          </div>
        </div>
      </px-col>
      <px-col v-else :span="18" class="water_col">
        <div class="waterdom borderRidus first_width"><modelTitle :title="'配额剩余量'" /><px-empty :image-size="100" /></div>
      </px-col>
    </px-row>
    <px-row style="height: 460px; margin-top: 16px">
      <px-col :span="8" class="water_col">
        <div class="waterdom borderRidus first_width">
          <modelTitle :title="`配额消耗`" />
          <div class="title-right" style="right: 32px">
            <px-tooltip effect="dark" content="导出图片">
              <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartsUpwChemistryRef')" />
            </px-tooltip>
            <px-tooltip effect="dark" content="导出数据">
              <px-button type="primary" text :icon="Document" @click="handleExport1" />
            </px-tooltip>
          </div>
          <div class="model_chart" style="margin-top: 16px">
            <chartsUpwChemistry ref="chartsUpwChemistryRef" :chartvalue="consume" width="'100%'" :height="'380px'" />
          </div>
        </div>
      </px-col>
      <px-col :span="8" class="water_col">
        <div class="waterdom borderRidus first_width">
          <modelTitle :title="`排放类别配额消耗占比`" />
          <div class="title-right" style="right: 32px">
            <px-tooltip effect="dark" content="导出图片">
              <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartsIndexUpwRef')" />
            </px-tooltip>
            <px-tooltip effect="dark" content="导出数据">
              <px-button type="primary" text :icon="Document" @click="handleExport2" />
            </px-tooltip>
          </div>
          <div class="model_chart" style="margin-top: 16px">
            <chartsIndexUpw ref="chartsIndexUpwRef" :chartvalue="firstPieList" :width="'100%'" :height="'380px'" />
          </div>
        </div>
      </px-col>
      <px-col :span="8" class="water_col">
        <div class="waterdom borderRidus">
          <modelTitle :title="'年度配额变化趋势'" />
          <div class="title-right" style="right: 32px">
            <px-tooltip effect="dark" content="导出图片">
              <px-button type="primary" text :icon="Download" @click="exportImageHandler('chartswwtRef')" />
            </px-tooltip>
            <px-tooltip effect="dark" content="导出数据">
              <px-button type="primary" text :icon="Document" @click="handleExport3" />
            </px-tooltip>
          </div>
          <div class="model_chart" style="margin-top: 16px">
            <chartswwt ref="chartswwtRef" :chartvalue="trend" style="width: 100%" :width="'100%'" :height="'380px'" />
          </div>
        </div>
      </px-col>
    </px-row>
  </div>
</template>
<script setup lang="ts">
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import chartsParent from "./components/chartsParent.vue";
import chartswwt from "./components/chartswwt.vue";
import chartsUpwChemistry from "./components/chartsUpwChemistry.vue";
import chartsIndexUpw from "./components/chartsIndexUpw.vue";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { accountingTemplatequery } from "@/api/doubleCarbonManage/accountingBoundary";
import { quotamonitor } from "@/api/doubleCarbonManage/quotaManage";
import { accountingEmissionDatagetCategoryPieBar } from "@/api/doubleCarbonManage/dataAnalysis";
import { Download, Document } from "@px-ui/icons-vue";
import { exportCanvasImg } from "@/utils/common";

const data = reactive({
  queryParams: {
    particularYear: "",
    level: null,
    templateId: ""
  },
  templateList: [],
  summary: {},
  consume: {},
  rank: {},
  trend: {},
  exportMonitor: {},
  firstPieList: [],
  firstData: {}
});
const liquidList = [
  { itemName: "全厂", itemValue: null },
  { itemName: "创新中心一期", itemValue: "创新中心一期" },
  { itemName: "创新中心二期", itemValue: "创新中心二期" }
];
const { firstData, firstPieList, exportMonitor, queryParams, templateList, summary, consume, rank, trend } = toRefs(data);
const handleQuery = () => {
  getList();
};
const resetQuery = () => {
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  console.log();
  queryParams.value.particularYear = end.getFullYear().toString();
  queryParams.value.level = null;
  queryParams.value.templateId = templateList.value[0]?.id;
  if (localStorage.getItem("facList")) {
    let faclist = JSON.parse(localStorage.getItem("facList"));
    if (faclist.length == 1) {
      facDisabled.value = true;
      queryParams.value.level = faclist[0].name;
      getList();
    } else if (faclist.length == 2) {
      facDisabled.value = false;
      queryParams.value.level = null;
      getList();
    }
  }
};
let facDisabled = ref(false);
onMounted(() => {
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  console.log();
  queryParams.value.particularYear = end.getFullYear().toString();
  accountingTemplatequery({
    pageNum: 1,
    pageSize: 999
  }).then((response: any) => {
    templateList.value = response.data;
    queryParams.value.templateId = templateList.value[0]?.id;
    if (localStorage.getItem("facList")) {
      let faclist = JSON.parse(localStorage.getItem("facList"));
      if (faclist.length == 1) {
        facDisabled.value = true;
        queryParams.value.level = faclist[0].name;
        getList();
      } else if (faclist.length == 2) {
        facDisabled.value = false;
        queryParams.value.level = null;
        getList();
      }
    }
  });
});
const { proxy }: any = getCurrentInstance();
const handleExport = () => {
  exportMonitor.value.name = "配额剩余量";
  proxy.download("post", "/energy/quota/exportMonitor", exportMonitor.value);
};
const handleExport1 = () => {
  exportMonitor.value.name = "配额消耗";
  proxy.download("post", "/energy/quota/exportMonitor", exportMonitor.value);
};
const handleExport2 = () => {
  firstData.value.name = "排放类别配额消耗占比";
  firstData.value.type = "pie";
  proxy.download("post", "/energy/quota/exportMonitor", firstData.value);
};
const handleExport3 = () => {
  exportMonitor.value.name = "年度配额消耗趋势";
  proxy.download("post", "/energy/quota/exportMonitor", exportMonitor.value);
};
const getList = () => {
  quotamonitor(queryParams.value).then(res => {
    console.log(res);

    exportMonitor.value = res;
    summary.value = res.summary;
    if (queryParams.value.level) {
      summary.value.levelConsume = summary.value?.levelConsume.filter(e => e.level == queryParams.value.level);
    }
    consume.value = res.consume;
    rank.value = res.rank;
    trend.value = res.trend;
  });
  accountingEmissionDatagetCategoryPieBar({
    dimension: "Y",
    startDate: `${queryParams.value.particularYear}-01-01 00:00:00`,
    endDate: `${queryParams.value.particularYear}-12-31 23:59:59`,
    level: queryParams.value.level,
    templateId: queryParams.value.templateId
  }).then(res => {
    console.log(res);
    firstData.value = res || {};
    if (res != null) {
      firstPieList.value = res.category;
    } else {
      firstPieList.value = [];
    }
  });
};

const chartsUpwChemistryRef = ref(null);
const chartsIndexUpwRef = ref(null);
const chartswwtRef = ref(null);
function exportImageHandler(key: string) {
  const map = {
    chartsUpwChemistryRef: chartsUpwChemistryRef.value.$el,
    chartsIndexUpwRef: chartsIndexUpwRef.value.$el,
    chartswwtRef: chartswwtRef.value.$el
  };
  const canvas = map[key].querySelector("canvas");
  exportCanvasImg(canvas);
}
</script>

<style scoped lang="scss">
.water_col {
  height: 100%;
}

.waterdom {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.first_width {
  width: calc(100% - 16px);
}

.model_chart {
  position: relative;
  width: 100%;
  height: calc(100% - 40px);

  .co2img {
    position: absolute;
    top: 32px;
    left: 22px;
    width: 32px;
    height: 32px;
  }

  .titlep {
    position: absolute;
    top: 29px;
    left: 70px;
    font-size: 16px;
    font-weight: 400;
    color: #000;
  }

  .titlevalue {
    position: absolute;
    top: 55px;
    left: 70px;

    .titlevalue1 {
      float: left;
      font-size: 20px;
      font-weight: 600;
      line-height: 28px;
      color: #3b82f6;
    }

    .titlevalue1span {
      font-size: 16px;
      font-weight: 400;
      line-height: 22px;
      color: #4f4f4f;
    }

    .titlevalue2 {
      float: left;
      margin-top: 5px;
      margin-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #f87171;
    }
  }

  .co2mian {
    position: absolute;
    top: 112px;
    left: 0;
    width: 100%;
    height: 92px;
  }

  .co2mianleft {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianleftp {
      width: calc(100% - 21px);
      height: 22px;
      padding-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
      border-right: 1px solid #cbcdd8;
    }
  }

  .co2mianright {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianrightp {
      width: calc(100% - 30px);
      height: 22px;
      padding-left: 45px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }
  }

  .co2mianleftp2 {
    margin-left: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #3b82f6;

    .co2mianleftp2span {
      font-size: 14px;
      font-weight: 400;
      color: #4f4f4f;
    }
  }

  .co2mianleftp3 {
    float: left;
    margin-left: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #000;

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #34d399;
    }
  }
}

.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 18px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 16px;
}

.percentage-value2 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
}

.percentage-label2 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
}

.percentage-value3 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
  color: #f00;
}

.percentage-label3 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #f00;
}

.jindu1 {
  margin: 24px 0 0 calc(50% - 73px);
}

.jindu2 {
  margin: 38px calc((100% - 103px) / 2);
}

.jindu1p {
  width: calc(100% - 24px);
  margin-top: 0;
  font-size: 16px;
  text-align: center;
}

.jindu2p {
  width: 100%;
  margin-top: -40px;
  font-size: 14px;
  text-align: center;
}

.title-right {
  position: absolute;
  top: 16px;
  right: 24px;
  display: flex;
  gap: 16px;
  align-items: center;

  .px-button {
    padding: 0;

    & + .px-button {
      margin-left: 0;
    }
  }
}
</style>
